package org.lagou.edu.config;

import com.github.vanroy.springdata.jest.JestElasticsearchTemplate;
import io.searchbox.client.JestClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;

/**
 * @author shiding
 */
@Configuration
@Slf4j
public class ElasticSearchConfig {

    @Value("${spring.elasticsearch.rest.username}")
    private String username;

    @Value("${spring.elasticsearch.rest.password}")
    private String password;

    @Value("${spring.elasticsearch.rest.client.connect-timeout}")
    private Integer connectTimeout;

    @Value("${spring.elasticsearch.rest.client.socket-timeout}")
    private Integer socketTimeout;

    /**
     * 间隔心跳时间
     */
    public static final int KEEP_ALIVE_MINUTES = 4;

    @Value("${spring.elasticsearch.rest.client.online-com.lagou.edu.service-heartbeat}")
    private Long heartBeatFreq;

    public static final String CLIENT_NAME = "RestHighLevelClient";

    @Bean
    public RestHighLevelClient restHighLevelClient(@Autowired RestClientBuilder restClientBuilder) {
        //设置密码
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
        RestHighLevelClient client = new RestHighLevelClient(restClientBuilder.setHttpClientConfigCallback(requestConfig -> {
            // 保持client 每 5分钟 发送数据保持http存活
            requestConfig.setKeepAliveStrategy((response, context) -> Duration.ofMinutes(KEEP_ALIVE_MINUTES).toMillis());
            requestConfig.setDefaultCredentialsProvider(credentialsProvider);
            // requestConfig
            RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
            requestConfigBuilder.setConnectTimeout(connectTimeout);
            requestConfigBuilder.setSocketTimeout(socketTimeout);
            requestConfig.setDefaultRequestConfig(requestConfigBuilder.build());
            return requestConfig;
        }));


        return client;
    }

    @Bean
    public JestElasticsearchTemplate jestElasticsearchTemplate(JestClient jestClient) {
        return new JestElasticsearchTemplate(jestClient);
    }
}
